import React from 'react';
import { Menu, Layout, Typography } from 'antd';
import { 
  HomeOutlined, 
  DatabaseOutlined, 
  QrcodeOutlined, 
  FileExcelOutlined, 
  LogoutOutlined, 
  UserOutlined, 
  SettingOutlined,
  ScanOutlined
} from '@ant-design/icons';
import { Link, useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { logoutUser } from '../redux/features/userSlice';
import './Sidebar.css';

const { Sider } = Layout;
const { Title } = Typography;

const Sidebar = ({ collapsed }) => {
  const location = useLocation();
  const dispatch = useDispatch();
  const { userInfo } = useSelector((state) => state.user);
  const isAdmin = userInfo?.role === 'admin';

  // 处理退出登录
  const handleLogout = async () => {
    try {
      await dispatch(logoutUser()).unwrap();
      // 重定向到登录页
      window.location.href = '/login';
    } catch (error) {
      console.error('退出登录失败:', error);
    }
  };

  // 菜单项
  const menuItems = [
    {
      key: 'home',
      icon: <HomeOutlined />,
      label: <Link to="/">首页</Link>,
    },
    {
      key: 'devices',
      icon: <DatabaseOutlined />,
      label: <Link to="/devices">设备管理</Link>,
    },
    {
      key: 'generate',
      icon: <QrcodeOutlined />,
      label: <Link to="/generate-qrcode">生成二维码</Link>,
    },
    {
      key: 'scan',
      icon: <ScanOutlined />,
      label: <Link to="/scan-qrcode">扫描二维码</Link>,
    },
    // 只有管理员可以看到导出和系统设置
    ...(isAdmin ? [
      {
        key: 'export',
        icon: <FileExcelOutlined />,
        label: <Link to="/export">导出数据</Link>,
      },
      {
        key: 'system',
        icon: <SettingOutlined />,
        label: <Link to="/system">系统设置</Link>,
      },
    ] : []),
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: <Link to="/profile">个人中心</Link>,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: <span onClick={handleLogout}>退出登录</span>,
    },
  ];

  return (
    <div className="sidebar-container">
      {!collapsed && (
        <div className="sidebar-header">
          <Title level={4} className="sidebar-title">
            导航菜单
          </Title>
        </div>
      )}
      <Menu
        mode="inline"
        selectedKeys={[location.pathname.split('/')[1] || 'home']}
        items={menuItems}
        className="sidebar-menu"
        theme="dark"
        defaultOpenKeys={['devices']}
      />
    </div>
  );
};

export default Sidebar;